import 'dart:convert';
import 'dart:core';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_niandaxue/component/base_components.dart';
import 'package:flutter_niandaxue/config/color.dart';
import 'package:flutter_niandaxue/config/font.dart';
import 'package:flutter_niandaxue/config/string.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/pages/exampaper/exam_paper_page.dart';
import 'package:flutter_niandaxue/pages/index_page.dart';
import 'package:flutter_niandaxue/pages/question/question_detail_page.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'package:fluttertoast/fluttertoast.dart';
enum Action {
  Ok,
  Cancel
}
class CourseQuestionPage extends StatefulWidget{
  final Course course;
  final bool isAddStudyFlag; // 是否加入了最近学习
  CourseQuestionPage({Key key,@required this.course,@required this.isAddStudyFlag}):super(key:key);

  @override
  State<StatefulWidget> createState() => new _CourseQuestionPage(course: this.course, isAddStudyFlag: this.isAddStudyFlag, key:this.key);
}

class _CourseQuestionPage extends State<CourseQuestionPage> with TickerProviderStateMixin {
  Course course;
  final bool isAddStudyFlag; // 是否加入了最近学习
  Key key;
  _CourseQuestionPage({this.course, this.isAddStudyFlag, this.key});
  TabController _tabController ;
  List<Widget> _tabs = [];
  List<Widget> _tableViewList = [];
  GlobalKey<ScaffoldState> _key = GlobalKey();
  List chapterList = [];
  int _selectedIndex;
  bool hasTopLoad = false;
  @override
  void initState() {
    super.initState();

    // 初始化tab导航栏控制器
    this._tabController = new TabController(length: _tabs.length, vsync:this);
    _tabController.addListener((){
      setState(() => _selectedIndex = _tabController.index);
    });
    // 1 加载表单数据
    chapterList.clear();
    _getChapterList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _courseTitle(), // 课程标题
        actions: <Widget>[
          RaisedButton.icon(
            color: KColor.primaryColor,
            icon: Image.asset('assets/icons/examPaper.png',width: 20, ),
            label: Text(KString.examPaperButton,
                style: TextStyle(
                    fontSize: 20
                ),
            ),
            onPressed:  () {
              Navigator.push(context, MaterialPageRoute(
                  builder:(context){
//                    return new CourseQuestionPage(course: course,);
                    return new ExamPaperPage(course: course, examPaperFlag: 1);
                  }
              ));
            },
          ),
        ],
      ),
      body: SafeArea(
        top: true,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              _buildRoot(),
            ],
          ),
        ),
    );
  }

  // 课程标题按钮
  Widget _courseTitle(){
    return Container(
      alignment: Alignment.center,
      child: MaterialButton(
        child: Text(course.name, style: KFont.font18,),
        onPressed: () {
          if(isAddStudyFlag){
            _openAlertDialog("是否从最近学习移除");
          } else{
            _openAlertDialog("是否加入到最近学习");
          }
        },
      ),
    );
  }

  // 打开弹框, 是否加入到最近学习
  Future _openAlertDialog(content) async {
    final action = await showDialog(
      context: context,
      barrierDismissible: false,//// user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
//          title: Text('提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context, Action.Cancel);
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () {
                _addCourseToStudy();
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildRoot() {
    if (!hasTopLoad) {
      return Center(
        child: Text('加载中...'),
      );
    } else {
      if(chapterList.length == 0){
          return Container(
            color: KColor.twoLeverPrimaryColor,
            height: MediaQuery.of(context).size.height - 100,
            child: NothingListView(),
          );
      }
      return Container(
        color: KColor.twoLeverPrimaryColor,
        height: MediaQuery.of(context).size.height - 100,
        child: Column(
          children: <Widget>[
            Container(
              height: 46,
              alignment: Alignment.centerLeft,
              child: TabBar(
                indicatorSize: TabBarIndicatorSize.label,
                labelColor: Colors.blueAccent,
                unselectedLabelColor: Colors.black,
                indicatorColor: KColor.twoLeverPrimaryColor,
                labelStyle: TextStyle(fontSize: 17),
                isScrollable: true,
                controller: _tabController,
                tabs: _tabs,
              ),
            ),
            Divider(color: KColor.primaryColor,),
            Expanded(
              flex: 1,
              child: TabBarView(
                children: _tableViewList,
                controller: _tabController,
              ),
            ),
          ],
        ),
      );
    }
  }
  _getChapterList() async {
    try{
      String formData = '/'+ course.code;
      request_get_json('chapter/listAll', formData:formData).then((val){
        var data = json.decode(val.toString());
        List rows = data['data'] as List;
        this.chapterList.addAll(rows) ;
        this._tabs.clear();
        this._tableViewList.clear();
        this._getTabList();
        setState(() {
          hasTopLoad = true;
          _tabController = new TabController(length: _tabs.length, vsync: this);
        });
      });
    }catch(e){}
  }
  _getTabList(){
    if(chapterList != null && chapterList.length > 0){
      for(int i = 0;i<chapterList.length;i++){
        Chapter _chapter = Chapter.fromJson(chapterList[i]);
        _tabs.add(new Tab(text: _chapter.smallName,));
        _tableViewList.add(
          new CourseQuestionPageColumn(course: course,chapter:_chapter),
        );
      }
    }
  }

  // 提示信息
  void _showToast(msg){
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
  }

  //  添加课程到最近学习
  _addCourseToStudy(){
    var formData = {'courseId': course.id};
    String url = isAddStudyFlag ? 'my/removeCourse': 'my/addCourse';
    request_post_json(url, formData: formData).then((val){
      var data = json.decode(val.toString());
      int status = data['status'];
      _showToast(data['msg']);
      if(status == 0){
        Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder:(context){
          return IndexPage();
        }), (check) => false);
      }
    });
  }
  @override
  void dispose() {
    this._tabController.dispose();
    super.dispose();
  }
}

/************************************************* 题目列表组件 *********************************************************/

class CourseQuestionPageColumn extends StatefulWidget{
  Course course;
  Chapter chapter;
  int questionFlag;
  CourseQuestionPageColumn({Key key,@required this.course,@required this.chapter, @required this.questionFlag}):super(key:key);
  @override
  State<StatefulWidget> createState() => new _CourseQuestionPageColumn(course: this.course, chapter: this.chapter, questionFlag:this.questionFlag, key:this.key);
}

class _CourseQuestionPageColumn extends State<CourseQuestionPageColumn> with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin{
  Course course;
  Chapter chapter;
  int questionFlag;
  Key key;
  _CourseQuestionPageColumn({this.course, this.chapter, this.questionFlag, this.key});

  int currentPage = 1;
  int totalPage = 1;
  int total = 0;
  List formList = [];
  final ScrollController _controller = new ScrollController();
  bool dataLoadFlag = false;
  String loadMoreText = "没有更多数据";
  TextStyle loadMoreTextStyle = new TextStyle(color: const Color(0xFF999999), fontSize: 14.0);

  @override
  void initState() {
    super.initState();
    this.formList.clear();
    this.currentPage = 1;
    // 1 加载表单数据
    this._getList();
    // 2 初始化滚动监听器，加载更多使用
    this._controller.addListener(() {
      if (this._controller.position.pixels == this._controller.position.maxScrollExtent) {
        this.loadMoreData(true);
      }
    });
  }

  /*
   * 构建内容
   */
  @override
  Widget build(BuildContext context) {
    return Center(
        child: RefreshIndicator(
          child: this.buildContent(),
          onRefresh: this._handleRefresh,
        )
    );
  }

  Widget buildContent() {
    if(!dataLoadFlag){
      return Center(
        child: Text(KString.loading),
      );
    }else{
      if (this.formList.length == 0) {
        return NothingListView();
      }
      return ListView.builder(
        itemBuilder: this._renderList,
        itemCount: this.formList.length + 1,
        controller: this._controller, //指明控制器加载更多使用
      );
    }
  }


  Widget _renderList(context, index) {
    String message = "${chapter.name} 题目：" + this.total.toString() + " 个";
    if (index == 0) {
      return Container(
        height: 30.0,
        padding: const EdgeInsets.only(left: 10.0),
        child: Row(
          children: <Widget>[
            Icon(Icons.book, size: 20.0,),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(left: 10),
                child: Text(message,
                  style: new TextStyle(
                    color: Colors.green, //字体颜色
                    fontSize: 15.0,
                    height: 1.5,
                    letterSpacing: 1.0, //字体间距
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
    if (index == this.formList.length+1) {
      return this._buildProgressMoreIndicator();
    }

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 1.0, horizontal: 1.0),
      margin: const EdgeInsets.only(bottom: 1.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          new BoxShadow(
            color: const Color(0xFFd0d0d0),
            blurRadius: 1.0,
            spreadRadius: 1.0,
            offset: Offset(2.0, 2.0),
          ),
        ],
      ),
      child: ListTile(
        title: Text(
          this.formList[index-1]['main'],
          overflow: TextOverflow.ellipsis,
          style: KFont.courseQuesTitleStyle,
        ),
        trailing: Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 20.0),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(
              builder:(context){
                return this.buildPageView(index - 1);
              }
          ));
        },
        selected: true,
      ),
    );
  }

  /*
   * 构建滑动视图
   */
  Widget buildPageView(curIndex) {
    var pageView = new PageView.builder(
      itemBuilder: ((context, startIndex) {
        String countMsg = (startIndex + 1).toString() + "/" + this.total.toString();
        Question question = Question.fromJson(this.formList[startIndex]);
        question.courseId = course.id;
        return new QuestionShowView(question: question,answerFlag: false, countMsg:countMsg,sourceType:2);
      }),
      itemCount: this.total,
      scrollDirection: Axis.horizontal,
      reverse: false,
      physics: PageScrollPhysics(parent: ClampingScrollPhysics()),
      controller: PageController(
        initialPage: curIndex,
        viewportFraction: 1,
        keepPage: true,
      ),
      onPageChanged: (index){
        int len = this.formList.length;
        if((len - index) < 3){
          this.loadMoreData(true);
        }
      },
    );
    return Scaffold(
        appBar: AppBar(
          title: Text('题目信息'),
        ),
        body: pageView
    );
  }

  // 延迟3秒后添加新数据， 模拟网络加载
  Future  _handleRefresh() async {
    dataLoadFlag = false;
    await Future.delayed(Duration(seconds: 1), () {
      setState(() {
        this.currentPage = 0;
        this.formList.clear();
        this.loadMoreData(false);
      });
    });
  }
  // 加载列表数据
  loadMoreData(bool flag) async {
    if(this.totalPage <= this.currentPage && this.totalPage > 0){
    }else{
      if(flag){
        setState(() {
          this.currentPage ++ ;
          this._getList();
        });
      }else{
        await Future.delayed(Duration(seconds: 1), () {
          setState(() {
            this.currentPage ++ ;
            this._getList();
          });
        });
      }
    }
  }
  /*
   * 加载更多进度条
   */
  Widget _buildProgressMoreIndicator() {
    return new Padding(
      padding: const EdgeInsets.all(15.0),
      child: new Center(
        child: new Text(this.loadMoreText, style: this.loadMoreTextStyle),
      ),
    );
  }

  void lastPrompt(){
    if(this.currentPage == this.totalPage){
      this.loadMoreText = "没有更多数据";
    }
  }

  void _getList() async {
    this.loadMoreText = "";
    var url = 'question/listPage';
    String result;
    var formPage = {'page':  {'current':this.currentPage,'size':15}, "questionFlag":this.questionFlag, 'courseCode':this.course.code, 'courseId':this.course.id,"chapterCode":chapter.code};
    request_post_json(url, formData:formPage).then((val) {
      var data = json.decode(val.toString());
      Page page = Page.fromJson(data['data']);

      setState(() {
        this.formList.addAll(page.records);
        this.totalPage = page.pages;
        this.total = page.total;
        this.currentPage = page.current;
        this.lastPrompt();
        dataLoadFlag = true;
      });
    });
  }

  MovieListState({Key key}) {
    // 固定写法，初始化滚动监听器，加载更多使用
    this._controller.addListener(() {
      var maxScroll = this._controller.position.maxScrollExtent;
      var pixel = this._controller.position.pixels;
      if (maxScroll == pixel && this.totalPage > this.currentPage && this.totalPage > 0) {
        setState(() {
          this.loadMoreText = "正在加载中...";
          this.loadMoreTextStyle = new TextStyle(color: const Color(0xFF4483f6), fontSize: 14.0);
        });
        this.loadMoreData(false);
      } else {
        setState(() {
          this.loadMoreText = "没有更多数据";
          this.loadMoreTextStyle = new TextStyle(color: const Color(0xFF999999), fontSize: 14.0);
        });
      }
    });
  }
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}



